package com.example.springsidedevelop.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;


@RestController
@RequestMapping("threadPool")
public class ThreadPoolController {

    @Autowired
    private AsyncTaskExecutor asyncTaskExecutor;

    private Logger logger = LoggerFactory.getLogger(ThreadPoolController.class);
    @GetMapping("")
    public void TestThread(){
        try {
            CountDownLatch latch = new CountDownLatch(5);
            //使用execute方法
            asyncTaskExecutor.execute(new Stats("任务A", 1000, latch));
            asyncTaskExecutor.execute(new Stats("任务B", 1000, latch));
            asyncTaskExecutor.execute(new Stats("任务C", 1000, latch));
            asyncTaskExecutor.execute(new Stats("任务D", 1000, latch));
            asyncTaskExecutor.execute(new Stats("任务E", 1000, latch));
            latch.await();// 等待所有人任务结束
            System.out.println("所有的统计任务执行完成:" + "");
        } catch (Exception e) {

        }
    }

    static class Stats implements Runnable  {
        String statsName;
        int runTime;
        CountDownLatch latch;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        public Stats(String statsName, int runTime, CountDownLatch latch) {
            this.statsName = statsName;
            this.runTime = runTime;
            this.latch = latch;
        }

        public void run() {
            try {
                System.out.println(statsName+ " do stats begin at "+ new Date());
                //模拟任务执行时间
                Thread.sleep(runTime);
                System.out.println(statsName + " do stats complete at "+ sdf.format(new Date()));
                latch.countDown();//单次任务结束，计数器减一
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
